package cn.ac.zing.server.hj212.test;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author：dcy
 * @name：SocketClient
 * @Date：2024/5/21 16:45
 */
public class SocketClient {
    public static void send(String ip, int port, String msg) throws Exception {
        try {
            Socket socket = new Socket(ip, port);
            OutputStream out = socket.getOutputStream();
            out.write((msg).getBytes(StandardCharsets.UTF_8));
            System.out.println("发送成功：" + ip + ":" + port + msg);
            socket.shutdownOutput();

            InputStream in = socket.getInputStream();
            BufferedInputStream bufferIn = new BufferedInputStream(in);
            byte[] buf = new byte[1024];
            try {
                int len;
                while ((len = bufferIn.read(buf)) != -1) {
                    System.out.print(new String(buf, 0, len, Charset.forName("UTF-8")));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                socket.shutdownInput();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.out.println("发送失败：" + ip + ":" + port + msg);
        }
    }

    public static void send(String ip, int port, byte[] bbuf) throws Exception {
        try {
            Socket socket = new Socket(ip, port);
            OutputStream out = socket.getOutputStream();
            out.write(bbuf);
            System.out.println("发送成功：" + ip + ":" + port + bbuf);
            socket.shutdownOutput();

            InputStream in = socket.getInputStream();
            BufferedInputStream bufferIn = new BufferedInputStream(in);
            byte[] buf = new byte[1024];
            try {
                int len;
                while ((len = bufferIn.read(buf)) != -1) {
                    System.out.print(new String(buf, 0, len, Charset.forName("UTF-8")));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                socket.shutdownInput();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.out.println("发送失败：" + ip + ":" + port + bbuf);
        }
    }
}
